package udp;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Scanner;

public class EchoClient02 {
    private DatagramSocket socket;
    private String serverIp;
    private int serverPort;

    public EchoClient02(String serveIp,int serverPort) throws Exception{
        this.serverIp=serveIp;
        this.serverPort=serverPort;
        socket=new DatagramSocket();
    }
    //1,控制台读取信息
    //2.使用DatagramPack封装 包含内容 长度 ip地址 端口号  发送信息
    //3.将返回的响应值封装为DatagramPacket 用recive方法读取信息
    //4.转换为字符串并打印响应信息
    public void start() throws Exception  {
        System.out.println("客户端启动");
        Scanner scanner=new Scanner(System.in);
        while(true){
            //1.控制台读取信息
            System.out.println(">");
            String request= scanner.next();
            //用DatagramPacket来封装请求信息 包含内容 长度 ip地址 端口号
            DatagramPacket reqPacket=new DatagramPacket(request.getBytes(), 
            request.getBytes().length,InetAddress.getByName(serverIp),serverPort);
            //用send方法发送信息
            socket.send(reqPacket);
            //接收返回信息
            DatagramPacket respPacket=new DatagramPacket(new byte[4096],4096);
            socket.receive(respPacket);
            String respon=new String(respPacket.getData(),
            respPacket.getOffset(),respPacket.getLength());
            System.out.println(respon);;

        }
    }

    public static void main(String[] args) throws Exception{
        EchoClient02 echoClient02=new EchoClient02("127.0.0.1", 9090);
        echoClient02.start();
    }


}
